package file

import (
	"context"
	"strings"
	// "os"
	"strconv"

	"mall/common/globalkey"
	"mall/service/attachment/model"
	"mall/service/attachment/rpc/internal/svc"
	"mall/service/attachment/rpc/internal/utils/errorhandler"
	"mall/service/attachment/rpc/types/attachment"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"

	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
	"github.com/zeromicro/go-zero/core/logx"
)

type BackendDeleteFileLogic struct {
	ctx           context.Context
	svcCtx        *svc.ServiceContext
	bucketManager *storage.BucketManager
	bucket        string
	logx.Logger
}

func NewBackendDeleteFileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendDeleteFileLogic {
	return &BackendDeleteFileLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendDeleteFileLogic) BackendDeleteFile(in *attachment.DeleteFileReq) (*attachment.BaseResp, error) {
	var ids []uint64
	var urls []string
	for _, id := range in.Ids {
		if i, err := strconv.ParseInt(id, 10, 64); err == nil && i > 0 {
			ids = append(ids, uint64(i))
			file, err := l.svcCtx.MediaFile.FindOneNoCache(l.ctx, nil, uint64(i))
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}

			if file.PostType == uint16(globalkey.AttachmentTypeDirectory) {
				filterMap := make(map[string]map[string][]any)
				filterMap[model.AttachmentColumns.PostParentID] = map[string][]any{
					"equalTo": []any{i},
				}
				_, count, err := l.svcCtx.MediaFile.GetList(l.ctx, model.M{}, 0, filterMap)
				if err != nil {
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}

				if count > 0 {
					logx.Errorw("delete directory failed, please check its children had been deleted",
						logx.Field("directoryId", id))
					return nil, errorx.NewInvalidArgumentError("file.deleteChildrenDesc")
				}
			}

			//收集file GUID
			if len(strings.TrimSpace(file.GUID)) > 0 {
				urls = append(urls, file.GUID)
			}
		}
	}

	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	for _, id := range ids {
		err = l.svcCtx.MediaFile.SoftDelete(l.ctx, tx, id)
		if err != nil {
			tx.Rollback()
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}
	}
	// 清理七牛云图片
	//todo: ulrs 路径是否需要进一步处理 需要检查测试
	if in.WithQiniu != nil && *in.WithQiniu > 0 && in.RetentionTime != nil && *in.RetentionTime > 0 && len(urls) > 0 {
		for _, url := range urls {
			mac := qbox.NewMac(l.svcCtx.Config.QiniuConf.AccessKey, l.svcCtx.Config.QiniuConf.SecretKey)
			cfg := &storage.Config{
				UseHTTPS:      l.svcCtx.Config.QiniuConf.UseHTTPS,      // 是否使用https域名进行资源管理
				UseCdnDomains: l.svcCtx.Config.QiniuConf.UseCdnDomains, // 上传是否使用CDN上传加速
			}

			// 指定空间所在的区域，如果不指定将自动探测
			// 如果没有特殊需求，默认不需要指定
			// cfg.Region=&storage.ZoneHuabei
			// switch l.svcCtx.Config.QiniuConf.Region {
			// case "z2":
			// 	cfg.Region = &storage.ZoneHuanan
			// }

			l.bucketManager = storage.NewBucketManager(mac, cfg)
			l.bucket = l.svcCtx.Config.QiniuConf.Bucket

			err := l.bucketManager.DeleteAfterDays(l.bucket, url, int(*in.RetentionTime))
			if err != nil {
				logx.Errorw("BackendDeleteFile DeleteAfterDays err", logx.Field("detail", err.Error()))
				return nil, err
			}
		}
	}

	tx.Commit()

	// 扫描程序清理已删除文件
	// for _, v := range files {
	// 	if v.Status == uint16(globalkey.AttachmentStatusPublish) {
	// 		err = os.RemoveAll(l.svcCtx.Config.NfsConf.PathPrefix + v.Path)
	// 		if err != nil {
	// 			return err
	// 		}
	// 	} else {
	// 		err = os.RemoveAll(l.svcCtx.Config.NfsConf.PathPrefix + v.Path)
	// 		if err != nil {
	// 			return err
	// 		}
	// 	}
	// }

	return &attachment.BaseResp{
		Msg: i18n.DeleteSuccess,
	}, nil
}
